package com.song.crud.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.song.crud.pojo.Employee;
import com.song.crud.pojo.Msg;
import com.song.crud.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2020/10/13 - the current system date.
 * 20:00 - the current system time.
 * Controller层 控制员工CRUD请求 与前端进行交互
 */
@Controller
public class EmployeeController {

    //controller层调用service层 帮我们处理业务逻辑
    @Autowired
    EmployeeService employeeService;


    @ResponseBody
    @RequestMapping(value="/emp/{ids}",method=RequestMethod.DELETE)
    public Msg deleteEmp(@PathVariable("ids")String ids){
        //批量删除
        if(ids.contains("-")){
            List<Integer> del_ids = new ArrayList<Integer>();
            String[] str_ids = ids.split("-");
            //组装id的集合
            for (String string : str_ids) {
                del_ids.add(Integer.parseInt(string));
            }
            employeeService.deleteBatch(del_ids);
        }else{
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
        }
        return Msg.success();
    }

    /**
     * 通过员工id查询信息
     * @return
     */
    @ResponseBody
    @RequestMapping(value="/emp/{id}",method = RequestMethod.GET)
    public Msg getEmp(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp",employee);
    }

    /**
     * 查询用户名是否可用
     * @return
     */
    @ResponseBody
    @RequestMapping("/checkuser")
    public Msg CheckUser(@RequestParam("empName") String empName){
        //先判断用户名是否是合法的表达式;
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})";
        if(!empName.matches(regx)){
            return Msg.fail().add("va_msg", "用户名必须是6-16位数字和字母的组合或者2-5位中文");
        }
        boolean flag = employeeService.checkUser(empName);
        if (flag){
            return Msg.success();
        }else {
            return Msg.fail().add("va_msg", "用户名不可用");
        }
    }

    /**
     * 保存员工信息
     * @return
     */
    @RequestMapping(value = "/emp",method = RequestMethod.POST)
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){
        Map<String,Object> map = new HashMap<String, Object>();
        if (result.hasErrors()){
            //验证失败，返回校正错误信息
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError error : fieldErrors) {
                System.out.println("错误字段名"+error.getField());
                System.out.println("错误信息"+error.getDefaultMessage());
                //将错误的信息封装到map中
                map.put(error.getField(),error.getDefaultMessage());
            }
            return Msg.fail().add("errors",map);
        }else {
            employeeService.saveEmp(employee);
            return Msg.success();
        }
    }

    /**
     * 保存修改后的员工信息
     * @param employee
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "emp/{empId}",method = RequestMethod.PUT)
    public Msg saveEmp(Employee employee){
        employeeService.updateEmp(employee);
        return Msg.success();
    }

    /**
     * 使用@ResponseBody注解帮助我们直接返回Jackson对象
     * @param pn 当前那一页数据的信息
     * @return
     */
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpWithJson(@RequestParam(value = "pn" ,defaultValue = "1") Integer pn){
        //引入分页插件 pn传入的页码 5 为一页显示多少条数据
        PageHelper.startPage(pn,5);
        List<Employee> employeeList =  employeeService.getAll();
        //使用PageInfo包装查询后的结果 只需将pageInfo交给页码就行 封装了页码的详细信息
        PageInfo pageInfo = new PageInfo(employeeList,5);
        return Msg.success().add("pageInfo",pageInfo);
    }

    /**
     * 查询员工数据（分页）
     * 获得所有员工信息 返回到list员工列表页面
     * Model 可以将数据放在请求域中
     *
     */
    //@RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn" ,defaultValue = "1") Integer pn,Model model){
        //引入分页插件 pn传入的页码 5 为一页显示多少条数据
        PageHelper.startPage(pn,5);
        List<Employee> employeeList =  employeeService.getAll();
        //使用PageInfo包装查询后的结果 只需将pageInfo交给页码就行 封装了页码的详细信息
        PageInfo pageInfo = new PageInfo(employeeList,5);
        model.addAttribute("pageInfo",pageInfo);
        //返回到list页面
        return "list";
    }

}
